package com.zunipe.ftpe;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Looper {
    private final ScheduledExecutorService scheduler;
    private final int executionsPerSecond;
    private final SelfRunnable task;

    public Looper(int countInSecond, SelfRunnable runnable) {
        this.executionsPerSecond = Math.max(1, countInSecond);
        this.task = runnable;
        this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread t = new Thread(r);
            t.setDaemon(false);
            t.setName("Looper-Thread");
            return t;
        });
    }

    public void start() {
        long intervalNanos = TimeUnit.SECONDS.toNanos(1) / executionsPerSecond;
        scheduler.scheduleAtFixedRate(() -> {
            try {
                task.run(this);
            } catch (Exception e) {
                System.err.println("Task execution failed: " + e.getMessage());
            }
        }, 0, intervalNanos, TimeUnit.NANOSECONDS);
    }

    public void stop() {
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(1, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
